<?php

namespace addons\miniform\controller;

use addons\third\model\Third;
use app\admin\model\miniform\Classs;
use app\admin\model\miniform\Meals;
use app\admin\model\miniform\Recharge;
use app\admin\model\miniform\School;
use app\admin\model\miniform\BaocanStatistics;
use app\admin\model\miniform\Student;
use app\admin\model\User;
use app\common\model\MoneyLog;
use think\Config;
use think\Db;

class Baocan extends Base
{

    protected $noNeedLogin = ['epay', 'mealStatistics', 'schoolTotal', 'classTotal', 'bcStatistics', 'bcStat', 'muAdd', 'tuisong', 'yanzheng'];

    /**
     * 获取身份
     */
    public function getUserGroup()
    {
        $user = User::get($this->auth->id);
        if(!$user){
            $this->error('用户不存在');
        }

        $student = Student::where('user_id', $this->auth->id)->find();
        // var_dump($student);
        if($student){
            $result['school_id'] = $student['school_id'];
            $result['class_id'] = $student['class_id'];

            $school = School::get($student['school_id']);
            if($school){
                $result['school_name'] = $school['name']; 
            }

            $classs = Classs::get($student['class_id']);
            if($classs){
                $result['class_name'] = $classs['name'];
            }

            $result['meal_set'] = $student['meal_set'];
            $result['meal_on'] = $student['meal_on'];
        }

        $result['group_id'] = $user['group_id'];
        $this->success('', $result);
    }

    /**
     * 学校列表
     */
    public function schoolList()
    {
        $data = School::field('id,name')->order('id desc')->select();
        $this->success('', $data);
    }

    /**
     * 获取班级
     */
    public function getClass()
    {
        $class_id = (int)$this->request->param('class_id');
        $classs = Classs::field(['id as class_id,name as class_name,school_id'])->where('id',$class_id)->find();
        if(!$classs){
            $this->error('班级不存在');
        }
        $school = School::get($classs['school_id']);
        if($school){
            $classs['school_name'] = $school['name']; 
        }
        $this->success('', $classs);
    }

    /**
     * 创建班级
     */
    public function classCreate()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        $name = $this->request->param('name');
        $class_name = $this->request->param('class_name');
        $school_id = (int)$this->request->param('school_id');

        if($this->auth->group_id != 2){
            $this->error('你不是老师');
        }
        $classs = Classs::get(['user_id'=>$this->auth->id]);
        if($classs){
            $this->error('你已创建过班级');
        }

        //生成邀请码
        $show_code = mt_rand(10,99).date('mds').mt_rand(100,999);
        $classs = Classs::create([
            'user_id' => $this->auth->id,
            'school_id' => $school_id,
            'name' => $class_name,
            'show_code' => $show_code
        ]);
        $class_id = $classs->id;

        //老师创建后报餐set和学校一致
        $school_inf = School::where('id',$school_id)->find();
        $classs_meal_set = isset($school_inf['meal_type']) ? $school_inf['meal_type'] : 1;
        $classs_meal_status = isset($school_inf['meal_status']) ? $school_inf['meal_status'] : 1;
        $student = Student::create([
            'user_id' => $this->auth->id,
            'school_id' => $school_id,
            'class_id' => $class_id,
            'meal_set' => $classs_meal_set,
            'name' => $name,
            'user_type' => 2,
            'meal_on' => $classs_meal_status
        ]);

        $this->success('创建成功', ['class_id' => $class_id,'show_code' => $show_code]);
    }

    /**
     * 加入班级
     */
    public function classJoin()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        $name = $this->request->param('name');
//        $class_id = (int)$this->request->param('class_id');
        // $school_id = (int)$this->request->param('school_id');
        $show_code = $this->request->param('show_code');

        if($this->auth->group_id == 2){
            $this->error('你不是学生');
        }

        $classs = Classs::where('show_code',$show_code)->find();
        if(!$classs){
            $this->error('班级不存在');
        }
        $school_id = $classs['school_id'];

        $student = Student::get(['user_id'=>$this->auth->id]);
        if($student){
            $this->error('你已加入班级');
        }

        $school = School::where('id',$school_id)->find();
        $meal_set = isset($school['meal_type']) && $school['meal_type'] ? $school['meal_type'] : 1;
        $student = Student::create([
            'user_id' => $this->auth->id,
            'school_id' => $school_id,
            'class_id' => $classs['id'],
            'name' => $name,
            'user_type' => 3,
            'meal_set' => $meal_set,
        ]);

        //更新身份
        $this->auth->group_id = 3;
        User::where('id', $this->auth->id)->update(['group_id'=>3]);

        $this->success('加入成功');
    }

    /**
     * 学生列表
     */
    public function studentList()
    {
        $class_id = (int)$this->request->param('class_id');
        $data = Student::field('id,user_id,name,meal_set,meal_on')
            ->where('user_type',3)
            ->where('class_id',$class_id)
            ->order('id desc')
            ->select();
        $this->success('', $data);
    }

    /**
     * 踢出班级
     */
    public function studentOut()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        $user_id = (int)$this->request->param('user_id');

        if($this->auth->group_id != 2){
            $this->error('你不是老师');
        }

        $student = Student::where(['user_id'=>$user_id])->delete();

        $this->success('踢出成功');
    }

    /**
     * 报餐设置
     */
    public function mealSet()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        $param = (int)$this->request->param('param');
        if($param<1 || $param>3){
            $this->error('参数错误');
        }

        $user_id = (int)$this->request->param('user_id');
        if($user_id){
            $student = Student::get(['user_id'=>$user_id]);
        }else{
            $student = Student::get(['user_id'=>$this->auth->id]);
        }

        if(!$student){
            $this->error('你还没有班级');
        }
        
        $meal_time1 = Config::get('miniform.meal_time1');
        $meal_time2 = Config::get('miniform.meal_time2');
        // $time1 = strtotime(date('Y-m-d')." $meal_time1:00:00");
        // $time2 = strtotime(date('Y-m-d',strtotime('+1 day'))." $meal_time2:00:00");
        $hour = date('H', time());
        if($hour>=12 && $hour<$meal_time1){
            $this->error('报餐时间未开始');
        }
        if($hour<12 && $hour>=$meal_time2){
            $this->error('报餐时间已结束');
        }

        $student->meal_set = $param;
        $student->save();

        $this->success('设置成功');
    }

    /**
     * 报餐开关
     */
    public function mealSwitch()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        $param = (int)$this->request->param('param');
        if($param<0 || $param>1){
            $this->error('参数错误');
        }
        
        $user_id = (int)$this->request->param('user_id');
        if($user_id>0 && $this->auth->group_id != 2){
            $this->error('你不是老师');
        }
        if($user_id == 0){
            $user_id = $this->auth->id;
        }

        $meal_time1 = Config::get('miniform.meal_time1');
        $meal_time2 = Config::get('miniform.meal_time2');
        // $time1 = strtotime(date('Y-m-d')." $meal_time1:00:00");
        // $time2 = strtotime(date('Y-m-d',strtotime('+1 day'))." $meal_time2:00:00");
        $hour = date('H', time());
        if($hour>=12 && $hour<$meal_time1){
            $this->error('报餐时间未开始');
        }
        if($hour<12 && $hour>=$meal_time2){
            $this->error('报餐时间已结束');
        }

        $student = Student::get(['user_id'=>$user_id]);
        if(!$student){
            $this->error('你还没有班级');
        }
        
        //查询学校是否禁止
        $school = School::get(['id'=>$student['school_id']]);
        if(!$school['meal_status']){
            $this->error('该学校暂禁止报餐');
        }

        $student->meal_on = $param;
        $student->save();

        $this->success('设置成功');
    }

    /**
     * 创建订单并支付
     */
    public function pay()
    {
        if (!$this->request->isPost()) {
            $this->error("请求错误");
        }
        $amount = $this->request->post('amount');
        $openid = '';

        $paytype = 'wechat';
        $method = 'miniapp';

        //创建订单
        $order = Recharge::submitOrder($amount, $this->auth->id);

        //非H5 支付,非余额
        if (in_array($method, ['miniapp', 'mp', 'mini'])) {
            $info = get_addon_info('third');
            if (!$info || !$info['state']) {
                $this->error("请在后台安装第三方登录插件");
            }
            $third = Third::where('platform', $paytype)
                ->where('apptype', $method)
                ->where('user_id', $this->auth->id)
                ->find();
            if (!$third) {
                $this->error("未找到第三方用户信息", 'bind');
            }
            $openid = $third['openid'];
        }
        try {
            $response = Recharge::pay($order->orderid, $this->auth->id, $paytype, $method, $openid);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success("请求成功", $response);
    }

    /**
     * 支付回调
     */
    public function epay()
    {
        $type = $this->request->param('type');
        $paytype = $this->request->param('paytype');
        if ($type == 'notify') {
            $pay = \addons\epay\library\Service::checkNotify($paytype);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            $data = $pay->verify();
            try {
                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                Recharge::settle($data['out_trade_no'], $payamount);
            } catch (\Exception $e) {
                \think\Log::write($e->getMessage(), 'epay');
            }
            echo $pay->success();
        } else {
            //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
            //$this->success("恭喜你！支付成功!", $order->archives->url);
        }
        return;
    }

    /**
     * 收支记录
     */
    public function moneyLog()
    {
        $param = $this->request->param();
        $limit = 10;
        if (isset($param['limit'])) {
            $limit = $param['limit'];
        }
        $data = MoneyLog::where('user_id', $this->auth->id)->order('id desc')->paginate($limit);
        foreach ($data as &$res) {
            $res['createtime'] = date('Y-m-d H:i:s', $res['createtime']);
        }
        $this->success('', $data);
    }

    /**
     * 获取余额
     */
    public function getMoney()
    {
        $user = User::get($this->auth->id);
        if(!$user){
            $this->error('用户不存在');
        }

        $result['money'] = $user['money'];
        $this->success('', $result);
    }

    /**
     * 学校报餐数据
     */
    public function schoolTotal()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        $type = (int)$this->request->param('type');
        $date = date('Y-m-d');

        $list = School::field(['id,name'])
            ->order ('name, id')
            ->select();
        foreach($list as &$res){
            $count = Meals::where('school_id', $res['id'])
                ->where('date', $date)
                ->where('type', $type)
                ->count();
            $res['total'] = $count;
        }
        $this->success('', $list);
    }

    /**
     * 班级报餐数据
     */
    public function classTotal()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        $school_id = (int)$this->request->param('school_id');
        $type = (int)$this->request->param('type');
        if(!$school_id){
            $this->error('参数错误');
        }
        $date = date('Y-m-d');

        $list = Classs::field(['id,name'])
            ->where('school_id', $school_id)
            ->order ('name, id')
            ->select();
        foreach($list as &$res){
            $count = Meals::where('class_id', $res['id'])
                ->where('date', $date)
                ->where('type', $type)
                ->count();
            $res['total'] = $count;
        }
        $this->success('', $list);
    }

    /**
     * 报餐统计（定时执行）
     */
    public function mealStatistics()
    {
        $date = date('Y-m-d');
        $hour = date('H');
        if($hour>13){
            $type = 2;  //晚餐
            $tip = '晚餐';
        }else{
            $type = 1;  //午餐
            $tip = '午餐';
        }
        //查询学校全部价格
        $school = School::where('meal_status',1)->select();
        $school_arr = [];
        foreach ($school as $item){
            $school_arr[$item['id']] = $item;
        }

        $list = Student::where('user_type','in','2,3')
            ->where('meal_on',1)
            ->order('class_id, user_id')
            ->select();
        foreach($list as $res){
            if($res['meal_set'] == $type || $res['meal_set'] == 3){
                $user = User::get($res['user_id']);
                //如果余额不足就要提醒
                if($user['money']<50){
                    $this->tuisong($user,$user['money']);
                    
                }
                if(isset($school_arr[$res['school_id']]['meal_amount']) && $user['money'] >= $school_arr[$res['school_id']]['meal_amount']){
                    $meal = Meals::where('date', $date)
                        ->where('type', $type)
                        ->where('user_id', $res['user_id'])
                        ->find();
                    if(!$meal){
                        Meals::create([
                            'user_id' => $res['user_id'],
                            'school_id' => $res['school_id'],
                            'class_id' => $res['class_id'],
                            'date' => $date,
                            'type' => $type,
                            'status' => 1,
                            'meal_amount' => $school_arr[$res['school_id']]['meal_amount'],
                        ]);

                        //更新余额
                        \app\common\model\User::money(-$school_arr[$res['school_id']]['meal_amount'], $res['user_id'], $tip.'扣款');
                    }
                }else{
                    //余额不足
                }
            }
        }
        echo('执行完成');
    }

    /**
	 * 分享小程序码
	 */
	public function qrcode()
	{
		$params = $this->request->post();
		$id = isset($params["show_code"]) ? $params["show_code"]:1;

        $path = 'pages/join/join?show_code='.$id;
        $savename = 'c'.$id.date('Ymdhis').'.png';

		$app_config = [
			'app_id' => Config::get('miniform.wx_appid'),
			'secret' => Config::get('miniform.wx_app_secret')
		];
		$app = \EasyWeChat\Factory::miniProgram($app_config);
		$response = $app->app_code->get($path);
		if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
			$savepath = ROOT_PATH.'public/uploads/qrcode';
			$filename = $response->saveAs($savepath, $savename);
			$filepath = $savepath.'/'.$filename;

			$result['path'] = $path;
			$result['filename'] = $filename;
			$result['base64'] = $this->imgBase64Encode($filepath);

			//删除文件
			unlink($filepath);
			$this->success('返回成功', $result);
		}else{
			$this->error(__('获取失败'));
		}
	}

    //图片base64
	private function imgBase64Encode($img = '', $imgHtmlCode = true)
	{
		//如果是本地文件
		if(strpos($img,'http') === false && !file_exists($img)){
			return $img;
		}
		//获取文件内容
		$file_content = file_get_contents($img);
		if($file_content === false){
			return $img;
		}
		$imageInfo = getimagesize($img);
		$prefiex = '';
		if($imgHtmlCode){
			$prefiex = 'data:' . $imageInfo['mime'] . ';base64,';
		}
		$base64 = $prefiex.base64_encode($file_content);
		return $base64;
	}
	
	/**
     * 报餐总额统计（在晚餐定时任务后执行）
     */
    public function bcStatistics()
    {
        $date = date('Y-m-d');
        $bcsta = new BaocanStatistics;
        //删除当天数据
        $bcsta->destroy(['date' => $date]);

        $date = date('Y-m-d');
        //获取全部学校信息
        $school = School::where('meal_status',1)->select();
        $school_arr = [];
        foreach ($school as $item){
            $school_arr[$item['id']] = $item;
        }
        //获取当天meals信息
        $meals = Meals::where('date', $date)->select();
        $statistics = [];
        foreach ($meals as $val){
            if($val['type'] == 1){
                //统计午餐
                if(isset($statistics[$val['school_id']]['lunch_num']) && $statistics[$val['school_id']]['lunch_num']){
                    $statistics[$val['school_id']]['lunch_num'] = $statistics[$val['school_id']]['lunch_num'] + 1;
                }else{
                    $statistics[$val['school_id']]['lunch_num'] = 1;
                }

                if(isset($statistics[$val['school_id']]['amount']) && $statistics[$val['school_id']]['amount']){
                    $statistics[$val['school_id']]['amount'] = $statistics[$val['school_id']]['amount'] + $val['meal_amount'];
                }else{
                    $statistics[$val['school_id']]['amount'] = $val['meal_amount'];
                }

            }elseif($val['type'] == 2){
                //统计晚餐
                if(isset($statistics[$val['school_id']]['dinner_num']) && $statistics[$val['school_id']]['dinner_num']){
                    $statistics[$val['school_id']]['dinner_num'] = $statistics[$val['school_id']]['dinner_num'] + 1;
                }else{
                    $statistics[$val['school_id']]['dinner_num'] = 1;
                }

                if(isset($statistics[$val['school_id']]['amount']) && $statistics[$val['school_id']]['amount']){
                    $statistics[$val['school_id']]['amount'] = $statistics[$val['school_id']]['amount'] + $val['meal_amount'];
                }else{
                    $statistics[$val['school_id']]['amount'] = $val['meal_amount'];
                }

            }
        }

        if($statistics){
            $statistics_arr = [];
            foreach ($statistics as $key=>$value){
                $value['school_name'] = isset($school_arr[$key]['name']) ? $school_arr[$key]['name'] : '';
                $value['date'] = $date;
                $value['school_id'] = $key;
                $statistics_arr[] = $value;
            }
            
            $bcsta = new BaocanStatistics;
            $bcsta->saveAll($statistics_arr);

        }
        
        echo('执行完成');

    }
    
        /**
     * 学校报餐统计接口
     */
    public function bcStat()
    {
        if (!$this->request->isPost()) {
            $this->error('请求错误');
        }
        $date_sta = $this->request->param('date_sta');
        $date_end = $this->request->param('date_end');
        $page_num = (int)$this->request->param('page_num');
        if(!$page_num){
            $page_num = 1;
        }
        $page_size = 50;//上线后要改成50条每页
        if(!$date_sta || !$date_end){
            //如果传值没有连贯的话,直接取当天数据
            $date_sta = $date_end = date('Y-m-d');
        }

        $list = BaocanStatistics::where('date','>=',$date_sta)->where('date','<=',$date_end)->order('date', 'desc')->select();
        $slice_sta = ($page_num-1)*$page_size;
        $slice_len = $page_size;
        if(count($list) >= $slice_sta){
            $list_re = array_slice($list,$slice_sta,$slice_len);
        }else{
            $list_re = [];
        }
        $total_num = count($list);
        $data_re['total'] = ceil($total_num/$page_size);
        $data_re['list'] = $list_re;

        $this->success('', $data_re);
    }
    
    public function tuisong($user,$amount1)
    {
        //获取用户token
        $third = Third::where('user_id', $user['id'])
                ->find();
        
        $openid = $third['openid'];
        $get_all_access_token = $third['access_token'];

        // //提交成功，触发信息推送
        // $data=[
        //     'touser'=>$openid,
        //     'template_id'=>'nRaXU0XnjDSfS1ZveCDY7PxHUiQuMD4eQ-dImt2LS9o',
        //     'url'=>$web_url = "http://".$_SERVER['SERVER_NAME'],
        //     'topcolor'=>"#FF0000",
        //     'data'=>array(
        //         'amount1' => '10',//商家
        //         'thing2' => '没钱',//商家电话
        //     )
        // ];
        
        //发送内容
        $data = [
            'touser'=>$openid,//接收者（用户）的 openid 
            'template_id'=>'nRaXU0XnjDSfS1ZveCDY7PxHUiQuMD4eQ-dImt2LS9o',//所需下发的订阅模板id
            'page'=>'/pages/user/user',//点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'miniprogram_state'=>'developer',//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
            'lang'=>'zh_CN',
            //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
            'data'=>[
                "amount1"=>[
                    'value' => $amount1
                ],
                "thing2"=>[
                    'value' => '余额不足，请及时充值'
                ]
            ]
        ];

        // $get_all_access_token = $this->get_all_access_token();

        $json_data=json_encode($data);//转化成json数组让微信可以接收
        $url="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$get_all_access_token;//模板消息请求URL

        // $res=$this->https_request($url,json_encode($json_data));//请求开始
        $res = self::curlPost($url,json_encode($data)) ;
        $res=json_decode($res,true);

        if($res['errcode']==0 && $res['errcode']=="ok"){
            return true;
        }else{
            return false;
        }
    }
    
    //发送post请求 小程序发送一次性订阅消息
    static function curlPost($url,$data)
    {
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $data;
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return $content;
    }


    public function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    public function get_all_access_token(){
        $appid = Config::get('miniform.wx_appid');
        $secret = Config::get('miniform.wx_app_secret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $res = $this->https_request($url);
        $res_arr = json_decode($res,true);
        $access_token = $res_arr['access_token'];
        return $access_token;
    }
    
    /*
     * Token: nRaXU0XnjDSfS1
     * EncodingAESKey:SqN6Pxx2PdsJOLd4b1NhM0oCD3UrZ713NezP3biVR9O
     * */
    public function yanzheng()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $echostr = $_GET["echostr"];
        $nonce = $_GET["nonce"];
        $token = 'nRaXU0XnjDSfS1';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if ($tmpStr == $signature ) {
            return json_encode(['echostr'=>$echostr]);
        } else {
            return false;
        }
    }


}
